// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const userId = wxContext.OPENID
  
  try {
    // 获取最近的周期记录
    const cyclesRes = await db.collection('cycles')
      .where({
        user_id: userId
      })
      .orderBy('start_date', 'desc')
      .limit(6)  // 获取最近6个周期用于分析
      .get()
    
    const cycles = cyclesRes.data || []
    
    // 获取当前日期
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    // 获取当前或最近的活跃周期
    let currentCycle = null
    let nextCycle = null
    let cycleDay = 0
    let daysUntilNext = 0
    let ovulationDate = null
    let cyclePhase = "未知"
    
    if (cycles.length > 0) {
      // 检查是否在活跃周期中
      currentCycle = cycles.find(c => {
        const startDate = new Date(c.start_date)
        const endDate = c.end_date ? new Date(c.end_date) : null
        
        if (!endDate) {
          // 周期尚未结束
          return startDate <= today
        }
        
        return startDate <= today && today <= endDate
      })
      
      // 如果当前有活跃周期
      if (currentCycle) {
        const startDate = new Date(currentCycle.start_date)
        cycleDay = Math.floor((today - startDate) / (24 * 60 * 60 * 1000)) + 1
        cyclePhase = "经期"
      } else {
        // 计算平均周期长度
        let avgCycleLength = 28 // 默认周期长度
        
        if (cycles.length >= 2) {
          let totalLength = 0
          let count = 0
          
          for (let i = 0; i < cycles.length - 1; i++) {
            const current = new Date(cycles[i].start_date)
            const next = new Date(cycles[i + 1].start_date)
            const length = Math.floor((current - next) / (24 * 60 * 60 * 1000))
            
            if (length > 0 && length < 60) { // 过滤异常值
              totalLength += length
              count++
            }
          }
          
          if (count > 0) {
            avgCycleLength = Math.round(totalLength / count)
          }
        }
        
        // 预测下一次周期
        const lastCycle = cycles[0]
        const lastStart = new Date(lastCycle.start_date)
        const predictedNextStart = new Date(lastStart)
        predictedNextStart.setDate(lastStart.getDate() + avgCycleLength)
        
        // 计算距离下次周期的天数
        daysUntilNext = Math.ceil((predictedNextStart - today) / (24 * 60 * 60 * 1000))
        
        // 如果距离下次周期在14天内，则处于黄体期
        if (daysUntilNext <= 14) {
          cyclePhase = "黄体期"
        } else {
          cyclePhase = "卵泡期"
        }
        
        // 计算预测的排卵日（通常是下次周期前14天）
        ovulationDate = new Date(predictedNextStart)
        ovulationDate.setDate(predictedNextStart.getDate() - 14)
        
        nextCycle = {
          predicted: true,
          start_date: predictedNextStart,
          cycle_length: avgCycleLength
        }
      }
    }
    
    // 获取今日记录
    const todayRecord = await db.collection('daily_records')
      .where({
        user_id: userId,
        date: _.gte(new Date(today.getFullYear(), today.getMonth(), today.getDate())),
        date: _.lt(new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1))
      })
      .get()
    
    // 获取本月日历数据
    const year = today.getFullYear()
    const month = today.getMonth()
    const firstDay = new Date(year, month, 1).getDay() // 本月第一天是周几
    const daysInMonth = new Date(year, month + 1, 0).getDate() // 本月天数
    
    // 生成日历数据
    const calendarDays = []
    
    // 添加空白格
    for (let i = 0; i < firstDay; i++) {
      calendarDays.push({ day: '', type: 'empty' })
    }
    
    // 添加日期
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(year, month, day)
      let type = ''
      
      // 标记今天
      if (day === today.getDate()) {
        type = 'today'
      }
      
      // 标记经期日
      const isPeriodDay = cycles.some(cycle => {
        const startDate = new Date(cycle.start_date)
        const endDate = cycle.end_date ? new Date(cycle.end_date) : null

        // 检查当前日期是否在周期范围内
        const currentDate = new Date(year, month, day)

        if (!endDate) {
          // 周期尚未结束，检查是否是周期开始日
          return startDate.getTime() === currentDate.getTime()
        }

        // 周期已结束，检查是否在周期范围内
        return currentDate >= startDate && currentDate <= endDate
      })
      
      if (isPeriodDay) {
        type = type ? `${type} period` : 'period'
      }
      
      // 标记排卵日
      if (ovulationDate && 
          ovulationDate.getFullYear() === year && 
          ovulationDate.getMonth() === month && 
          ovulationDate.getDate() === day) {
        type = type ? `${type} ovulation` : 'ovulation'
      }
      
      calendarDays.push({ day, type })
    }
    
    return {
      status: 'success',
      data: {
        currentCycle,
        nextCycle,
        cycleDay,
        daysUntilNext,
        cyclePhase,
        ovulationDate,
        todayRecord: todayRecord.data[0] || null,
        calendarDays,
        currentYear: year,
        currentMonth: month + 1
      }
    }
  } catch (err) {
    return {
      status: 'error',
      message: err.message,
      error: err
    }
  }
} 